/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cheat.administration;

import java.util.Date;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

/**
 * Provides the functionality related to management of the assignment sharing repository.
 *
 * @author Keith Shie
 */
@Stateless
public class RepositoryManagerBean implements RepositoryManagerRemote {

  @PersistenceUnit(unitName = "CheatApp-ejbPU")
  private EntityManagerFactory emf;

  private static Logger logger = Logger.getLogger(RepositoryManagerBean.class.getPackage().getName());

  /**
   * Retrieve the statistics of the assignment sharing repository.
   *
   * @return statistics of the repository.
   */
  public RepositoryStatistics getStatistics() {
    logger.finer( "getStatistics: start" );
    final RepositoryStatistics info = new RepositoryStatistics();
    
    final EntityManager em = emf.createEntityManager();

    info.setAssignmentCount( (Long) em.createQuery( "select count(a) from AssignmentProperty a where a.deleted = false").getSingleResult() );
    info.setDeletedAssignmentCount( (Long) em.createQuery( "select count(a) from AssignmentProperty a where a.deleted = true").getSingleResult());
    info.setAuthorCount( (Long) em.createQuery( "select count(distinct p) from Person p, in (p.asgnPropCollection) a").getSingleResult());
    info.setUserCount( (Long) em.createQuery( "select count(u) from RegisteredUser u").getSingleResult());
    info.setNewestAssignment( (Date) em.createQuery( "select max(a.updDt) from AssignmentProperty a where a.deleted = false").getSingleResult());
    info.setOldestAssignment( (Date) em.createQuery( "select min(a.createDt) from AssignmentProperty a where a.deleted = false").getSingleResult());

    logger.finer( "getStatistics: start" );
    return info;
  }
}
